/****************************************************************************************
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalDcPublicConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> <br>
 *  资费生失效时间校验
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年2月25日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.attr.handler <br>
 */

public class FeedateAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {

    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        Map<String, Object> loginExtParams = loginInfo.getUserInfo().getExtParams();
        String nodeCode = Optional.ofNullable(loginExtParams).map(m -> m.get("nodeCode")).orElse("").toString();
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "isInitPageRenderFlag");
        if (KiteStringUtils.isNotEmpty(value) && !KiteStringUtils.isEqual(value, attr.getValue()) && !KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            // 传入的是生效时间
            if (KiteStringUtils.isEqual(attr.getFieldName(), LocalKeyConsts.STARTING_DATE_FIELD_NAME)) {
                KiteAttr endDateKiteAttr = inst.getAttr(LocalKeyConsts.END_DATE_FIELD_NAME);

                if (Objects.nonNull(endDateKiteAttr) && KiteStringUtils.isNotEmpty(endDateKiteAttr.getValue())) {
                    String endDate = endDateKiteAttr.getValue();
                    if (DateFormatUtils.compareDate(endDate, value, DateFormatUtils.DATE_TIME_FORMAT)<0) {
                        //业务变更初始化
                        if (ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(data.getServiceOfferId())
                            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))
                            && !"workOrder".equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), "initSource"))) {
                            return;
                        }
                        //特殊处理：业务变更  勾选资费变更后 选择 ‘作废’操作后 失效时间会变为系统当前时间，后续业务变更的签订/重提场景暂时考虑不需要拦截 ，待后续优化
                        if(!(KiteStringUtils.equalsAny(data.getServiceOfferId(),"2826", "1047", "1048", "1003", "1004", "1014", "1114", "1214", "1314")
                            && KiteStringUtils.isNotEmpty(nodeCode))) {
                            //ErrorConsts.BUSI_COMMON_ERROR.throwOut("生效时间不能大于失效时间，请重新输入！");
                          //到期处理方式
                            KiteAttr expirTreatment = inst.getAttr("210004553");
                          //包月周期
                            KiteAttr CycleMonthsAttr = inst.getAttr("200003242");
                            //到期方式为如下两种时，会重新计算失效时间，所以可以不判断
                            if (Objects.nonNull(expirTreatment) && KiteStringUtils.equalsAny(expirTreatment.getValue(), LocalKeyConsts.END_UP_IN_PERIOD_TERMINATED, LocalKeyConsts.END_UP_IN_PERIOD_STOPPED)
                                && Objects.nonNull(CycleMonthsAttr) && KiteStringUtils.isNotEmpty(CycleMonthsAttr.getValue()) ) {
                                return;
                            }
                            BssException.throwOut("资费生失效时间校验", "资费生失效时间校验", "生效时间不能大于失效时间，请重新输入！");
                        }
                    }
                }
            }
            else if (KiteStringUtils.isEqual(attr.getFieldName(), LocalKeyConsts.END_DATE_FIELD_NAME)) {
                KiteAttr startDateKiteAttr = inst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
                if (Objects.nonNull(startDateKiteAttr) && KiteStringUtils.isNotEmpty(startDateKiteAttr.getValue())) {
                    String startDate = startDateKiteAttr.getValue();

                    /** 0923资费变更校验优化需求
                     * 对于存量已经生效的资费，从资费模块点击“编辑”按钮进去修改存量已生效的资费的时候：
                     * 1、去掉原校验规则：生效时间需要早于失效时间。
                     * 2、限制失效时间最早只能选择T-1月的最后一天，其中T为当前操作的月份。
                     * 3、前面两个规则仅仅针对月租类型的资费类型做调整。
                     */
                    KiteOfferInst offerInst = (KiteOfferInst) inst;
                    Map<String, Object> offerMap = Optional.ofNullable(ProdFeeCache.get(offerInst.getOfferId())).map(Offer::getOfferMap).orElse(null);
                    if (KiteStringUtils.equals("", KiteMapUtils.getString(offerMap, "payType")) && ActionType.K.equals(inst.getActionType()) || ActionType.M.equals(inst.getActionType())) {
                        String selectValue = value.substring(0, 10);
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateFormatUtils.DATE_FORMAT);
                        LocalDate localDate = null;
                        try {
                            localDate = LocalDate.parse(selectValue, dtf);
                        } catch (Exception e) {
                            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                        }
                        if(localDate != null) {

                            /*
                             * 天津互联网附加商品，失效时间只能选择 x月月底最后一天，x无限制
                             */

                            KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(data.getSceneInstId());
                            String mainOfferId = querySceneInstService.getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId()).getOfferId();
                            String province = Optional.ofNullable(loginInfo.getUserInfo()).map(UserInfo::getPostProvinceNbr).orElse(null);
                            if(KiteStringUtils.isEqual(data.getServiceOfferId(), "1024") && KiteStringUtils.isEqual(mainOfferId, "10002224")
                                && KiteStringUtils.isEqual(province, LocalKeyConsts.PROVINCE_TIANJIN) && !KiteStringUtils.isEqual(inst.getSpecId(), "10002224")) {
                                LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
                                if(!lastDay.isEqual(localDate)) {
                                    BssException.throwOut("资费生失效时间校验", "资费生失效时间校验", "失效时间只能选择任意月的月底最后一天");
                                }
                            } else {
                                // T-1月的最后一天，其中T为当前操作的月份
                                LocalDate minLocalDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).plusDays(-1);
                                if(localDate.isBefore(minLocalDate)) {
                                    BssException.throwOut("资费生失效时间校验", "资费生失效时间校验", "失效时间最早只能选择上个月的最后一天");
                                }
                            }
                        }
                    } else {
                        if (DateFormatUtils.compareDate(value, startDate, DateFormatUtils.DATE_TIME_FORMAT)<0) {
                            //业务变更初始化
                            if (ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(data.getServiceOfferId())
                                && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))
                                && !"workOrder".equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), "initSource"))) {
                                return;
                            }
                            //特殊处理：业务变更  勾选资费变更后 选择 ‘作废’操作后 失效时间会变为系统当前时间，后续业务变更的签订/重提场景暂时考虑不需要拦截 ，待后续优化
                            if(!(KiteStringUtils.equalsAny(data.getServiceOfferId(),"2826", "1047", "1048", "1003", "1004", "1014", "1114", "1214", "1314")
                                && KiteStringUtils.isNotEmpty(nodeCode))) {
                                // ErrorConsts.BUSI_COMMON_ERROR.throwOut("生效时间不能大于失效时间，请重新输入！");
                                BssException.throwOut("资费生失效时间校验", "资费生失效时间校验", "生效时间不能大于失效时间，请重新输入！");
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void set(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        if (KiteStringUtils.isNotEmpty(value)) {
            Date date = DateFormatUtils.parseStrToDate(value);
            // 传入的是生效时间
            if (KiteStringUtils.isEqual(attr.getFieldName(), LocalKeyConsts.STARTING_DATE_FIELD_NAME)) {
                value = DateFormatUtils.formatDate(DateFormatUtils.getStartOfDay(date), DateFormatUtils.DATE_TIME_FORMAT);
            }
            else if (KiteStringUtils.isEqual(attr.getFieldName(), LocalKeyConsts.END_DATE_FIELD_NAME)) {
                value = DateFormatUtils.formatDate(DateFormatUtils.getEndOfDay(date), DateFormatUtils.DATE_TIME_FORMAT);
            }
        }
        super.set(attr, inst, value, data);
    }

    @Override
    public void after(KiteAttr attr, KiteInst inst, AttrData data){
        String offerId = inst.getSpecId();
        // 得到5G产品的附加产品，判断是否5G产品
        List<DcPublic> dcList = DcPublicCache.getByPkey(LocalDcPublicConsts.DC_20210520401, offerId);
        if (KiteListUtils.isNotEmpty(dcList)) {
            String fileName = attr.getFieldName();
            // 一次性资费 安装调测-100000000017339、运营增值服务-100000000017337、覆盖增强服务-100000000017334
            if (KiteStringUtils.equalsAny(offerId, "100000000017339", "100000000017337", "100000000017334")) {
                if ("200000172".equals(fileName) || "200000173".equals(fileName)) {
                    attr.setIsEdit(KeyConsts.IFTRUE_F);
                    attr.setAttrValueTypeId("98O");
                }
            }
            else {
                if ("200000172".equals(fileName) || "200000173".equals(fileName)) {
                    attr.setIsEdit(KeyConsts.IFTRUE_T);
                    attr.setAttrValueTypeId("98O");
                }
            }
        }
        super.after(attr, inst, data);
    }



}
